package com.project.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.project.bean.StudentBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class JSONServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        List<StudentBean> stuList= new ArrayList<>();
        stuList.add(new StudentBean(1,"文林挥","18880451371", LocalDate.parse("1990-09-12")));
        stuList.add(new StudentBean(2,"张强","18880451371", LocalDate.parse("1990-09-12")));
        stuList.add(new StudentBean(3,"刘文龙","13990837347", LocalDate.parse("1990-09-12")));
        stuList.add(new StudentBean(4,"吴亦凡","13608234365", LocalDate.parse("1990-09-12")));
        stuList.add(new StudentBean(5,"刘英徐","17775933249", LocalDate.parse("1990-09-12")));
        ObjectMapper om= new ObjectMapper();
        om.registerModule(new JavaTimeModule());
        //将集合转化为json字符串
//        String student = om.writeValueAsString(stuList);
//        resp.getWriter().println(student);
        //简写为以下方法
        om.writeValue(resp.getWriter(),stuList);
    }
}
